// pages/payment_password_reset/index.js
Page({
  data: {
    navBarHeight: 0,
    contentTop: 0,
    bottomSafeArea: 0,
    
    phoneNumber: '',
    phoneVerified: false,
    oldPassword: '',
    oldPasswordArray: ['', '', '', '', '', ''],
    
    // 步骤控制
    currentStep: 1, // 1: 验证身份, 2: 验证原密码
    
    // 焦点控制
    focusOld: false,
    
    // 是否跳过原密码验证
    skipOldPassword: false,
    
    loading: false
  },

  onLoad(options) {
    // 计算导航栏高度
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    // 检查是否是首次设置密码模式（跳过原密码验证）
    const skipOldPassword = options.skipOldPassword === 'true'
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight + 10, // 增加10px间距避免内容被遮挡
      bottomSafeArea,
      skipOldPassword
    })

    // 如果是跳过原密码验证模式，需要再次验证用户确实未设置密码
    if (skipOldPassword) {
      this.verifyNoPasswordSet()
    }
  },

  // 验证用户确实未设置密码
  async verifyNoPasswordSet() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'verifyPaymentPassword',
        data: {
          checkOnly: true
        }
      })

      if (result.result.code !== 'NO_PASSWORD_SET') {
        // 用户已设置密码，不允许跳过验证
        wx.showModal({
          title: '安全提示',
          content: '检测到您已设置支付密码，无法跳过密码验证。请返回输入密码或选择忘记密码。',
          showCancel: false,
          confirmText: '返回',
          success: () => {
            wx.navigateBack()
          }
        })
      }
    } catch (error) {
      console.error('验证密码状态失败:', error)
      wx.showModal({
        title: '提示',
        content: '验证失败，请重试',
        showCancel: false,
        confirmText: '返回',
        success: () => {
          wx.navigateBack()
        }
      })
    }
  },

  // 微信手机实时验证
  async getRealtimePhoneNumber(e) {
    console.log('手机实时验证回调:', e.detail)
    
    // 修复errMsg检查，实际返回的是 getPhoneNumber:ok
    if (e.detail.errMsg !== 'getPhoneNumber:ok' && e.detail.errMsg !== 'getRealtimePhoneNumber:ok') {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none'
      })
      return
    }

    const { code } = e.detail
    if (!code) {
      wx.showToast({
        title: '获取验证码失败',
        icon: 'none'
      })
      return
    }

    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      wx.showLoading({
        title: '验证中...',
        mask: true
      })

      const result = await wx.cloud.callFunction({
        name: 'verifyPhoneNumber',
        data: {
          code: code
        }
      })

      wx.hideLoading()

      if (result.result.success) {
        this.setData({
          phoneNumber: result.result.data.phoneNumber,
          phoneVerified: true
        })

        wx.showToast({
          title: '验证成功',
          icon: 'success'
        })

        // 如果是跳过原密码验证模式，直接跳转到密码设置页面
        if (this.data.skipOldPassword) {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/payment_password_set/index?mode=set&phone=' + this.data.phoneNumber
            })
          }, 1500)
        } else {
          // 延迟跳转到原密码验证步骤
          setTimeout(() => {
            this.setData({
              currentStep: 2
            })
          }, 1500)
        }

      } else {
        wx.showToast({
          title: result.result.message || '验证失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('手机验证失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '验证失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 进入下一步（验证原密码）
  nextStep() {
    if (!this.data.phoneVerified) {
      wx.showToast({
        title: '请先完成手机验证',
        icon: 'none'
      })
      return
    }

    this.setData({
      currentStep: 2
    })
  },

  // 获取原密码输入框焦点
  getFocusOld() {
    this.setData({
      focusOld: true
    })
  },

  // 输入原密码
  onOldPasswordInput(e) {
    const value = e.detail.value
    const password = value.replace(/[^0-9]/g, '').slice(0, 6)
    
    const passwordArray = Array(6).fill('').map((_, index) => {
      return password[index] || ''
    })
    
    this.setData({
      oldPassword: password,
      oldPasswordArray: passwordArray
    })
    
    // 如果输入了6位密码，自动失去焦点
    if (password.length === 6) {
      this.setData({
        focusOld: false
      })
    }
  },

  // 验证原密码
  async verifyOldPassword() {
    const { oldPassword } = this.data

    if (!oldPassword || !/^\d{6}$/.test(oldPassword)) {
      wx.showToast({
        title: '请输入6位数字密码',
        icon: 'none'
      })
      return
    }

    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      wx.showLoading({
        title: '验证中...',
        mask: true
      })

      const result = await wx.cloud.callFunction({
        name: 'verifyPaymentPassword',
        data: {
          password: oldPassword
        }
      })

      wx.hideLoading()

      if (result.result.success) {
        wx.showToast({
          title: '验证成功',
          icon: 'success'
        })

        // 跳转到密码设置页面，并传递返回层级参数
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/payment_password_set/index?mode=reset&phone=' + this.data.phoneNumber + '&redirectDelta=2'
          })
        }, 1500)

      } else {
        wx.showToast({
          title: result.result.message || '密码错误',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('验证原密码失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: '验证失败，请重试',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 返回上一步
  goBack() {
    if (this.data.currentStep === 2) {
      this.setData({
        currentStep: 1,
        oldPassword: '',
        oldPasswordArray: ['', '', '', '', '', '']
      })
    } else {
      wx.navigateBack()
    }
  },

  // 返回按钮
  handleBack() {
    this.goBack()
  }
})